package com.javaee.ejb.jms;

import com.javaee.ejb.entity.ConversationMessage;
import com.javaee.ejb.jms.remote.ConversationMessageQueueSenderRemote;
import javax.ejb.Stateful;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * Session Bean implementation class ConversationMessageQueueSender
 */
@Stateful
public class ConversationMessageQueueSender implements
		ConversationMessageQueueSenderRemote {

	private QueueConnectionFactory connectionFactory;
	private Queue queue;

	/**
	 * Default constructor.
	 */
	public ConversationMessageQueueSender() {
		try {
			InitialContext context = new InitialContext();
			connectionFactory = (QueueConnectionFactory) context.lookup("JQCF");
			queue = (Queue) context.lookup("sampleQueue");
			context.close();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	public void postMessage(ConversationMessage conversationMessage) {

		// Ajout du message dans la file
		try {

			QueueConnection connection = connectionFactory
					.createQueueConnection();
			QueueSession session = connection.createQueueSession(false,
					Session.DUPS_OK_ACKNOWLEDGE);

			QueueSender sender = session.createSender(queue);
			ObjectMessage objMsg = session
					.createObjectMessage(conversationMessage);
			sender.send(objMsg);

			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
